<template>
  <div class="agency-home-container">
    <!-- 顶部横幅 -->
    <div class="banner">
      <div class="banner-content">
        <h1>{{ agencyInfo.travelAgencyName }}</h1>
        <p class="slogan">探索世界，从心出发 ✈️</p>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 左侧内容区 -->
      <div class="left-content">
        <!-- 旅行社信息卡片 -->
        <div class="info-card">
          <div class="card-header">
            <div class="audit-status">
              <el-tag
                :type="agencyInfo.auditStatus === '通过' ? 'success' :
                        agencyInfo.auditStatus === '未通过' ? 'danger' : 'warning'">
                <i class="el-icon-s-check"></i>
                {{ agencyInfo.auditStatus || '未审核' }}
              </el-tag>
            </div>
            <h2 class="info-title">
              <i class="el-icon-office-building"></i> 旅行社信息
            </h2>
            <div class="edit-toggle">
              <el-button
                type="primary"
                size="small"
                @click="toggleEdit"
                :icon="isEditing ? 'el-icon-close' : 'el-icon-edit'"
                round
              >
                {{ isEditing ? '取消编辑' : '编辑信息' }}
              </el-button>
            </div>
          </div>

          <div class="info-content">
            <!-- 旅行社头像 -->
            <el-form-item label="旅行社头像：">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/mw/upload/agencyAvatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
              :data="{ agencyId: agencyInfo.travelAgencyId }"
              :auto-upload="true"
              :on-progress="handleAvatarProgress"  
              :on-error="handleAvatarError">
                <template v-if="agencyInfo.travelAgencyAvatar">
                  <img :src="agencyInfo.travelAgencyAvatar" class="avatar">
                  <div class="avatar-hover">
                    <i class="el-icon-upload"></i>
                    <span>更换头像</span>
                  </div>
                </template>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!-- 旅行社名称 -->
            <el-form-item label="👤旅行社名称：">
              <el-input
                v-if="isEditing"
                v-model="agencyInfo.travelAgencyName"
                placeholder="请输入旅行社名称"
              />
              <span v-else>{{ agencyInfo.travelAgencyName }}</span>
            </el-form-item>

            <!-- 联系电话 -->
            <el-form-item label="📱联系电话：">
              <el-input
                v-if="isEditing"
                v-model="agencyInfo.officePhone"
                placeholder="请输入联系电话"
              />
              <span v-else>
                <i class="el-icon-phone"></i> {{ agencyInfo.officePhone }}
              </span>
            </el-form-item>

            <!-- 电子邮箱 -->
            <el-form-item label="📧电子邮箱：">
              <el-input
                v-if="isEditing"
                v-model="agencyInfo.officeEmail"
                placeholder="请输入电子邮箱"
              />
              <span v-else>
                <i class="el-icon-message"></i> {{ agencyInfo.officeEmail }}
              </span>
            </el-form-item>
           <el-form-item label="🗺️所在地区：">
              <el-select
                v-if="isEditing"
                v-model="selectedProvince"
                placeholder="请选择省份"
                filterable
                @change="handleProvinceChange"
                style="width: 120px; margin-right: 10px;"
              >
                <el-option v-for="item in provinceOptions" :key="item" :label="item" :value="item" />
              </el-select>
              <el-select
                v-if="isEditing"
                v-model="selectedCity"
                placeholder="请选择城市"
                filterable
                :disabled="!selectedProvince"
                style="width: 120px;"
              >
                <el-option v-for="item in cityOptions" :key="item" :label="item" :value="item" />
              </el-select>
              <span v-else>
                <i class="el-icon-location"></i> {{ agencyInfo.province }} {{ agencyInfo.city }}
              </span>
            </el-form-item>
            <!-- 常用地址 -->
            <el-form-item label="📍🏠常用地址：">
              <el-input
                v-if="isEditing"
                v-model="agencyInfo.officeAddress"
                placeholder="请输入常用地址"
                type="textarea"
                :rows="2"
              />
              <span v-else>
                <i class="el-icon-location-information"></i> {{ agencyInfo.officeAddress }}
              </span>
            </el-form-item>

            <!-- 旅行社简介 -->
            <el-form-item label="💭旅行社简介：">
              <el-input
                v-if="isEditing"
                v-model="agencyInfo.travelAgencyIntroduction"
                placeholder="请输入旅行社简介"
                type="textarea"
                :rows="4"
              />
              <div v-else class="description-text">
                <p>{{ agencyInfo.travelAgencyIntroduction }}</p>
              </div>
            </el-form-item>

              <!-- 编辑模式下的操作按钮 -->
              <div v-if="isEditing" class="form-actions">
                <el-button type="primary" @click="saveInfo" icon="el-icon-check">保存更改</el-button>
                <el-button @click="cancelEdit" icon="el-icon-refresh-left">取消</el-button>
              </div>
          </div>
        </div>

        <!-- 跟团游报名信息列表 -->
        <div class="registration-card">
          <h2 class="info-title">
            <i class="el-icon-tickets"></i> 跟团游报名信息
          </h2>
          <div class="table-header">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索姓名"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
          <el-table
            :data="registrationList"
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column prop="userName" label="用户姓名" width="120"></el-table-column>
            <el-table-column prop="groupTourName" label="跟团游名称" width="180"></el-table-column>
            <el-table-column prop="userPhone" label="联系电话" width="150"></el-table-column>
            <el-table-column prop="transactionAmount" label="交易金额" width="120">
              <template #default="scope">
                ¥{{ scope.row.transactionAmount }}
              </template>
            </el-table-column>
            <el-table-column prop="registrationTime" label="报名时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.registrationTime) }}
              </template>
            </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button 
                    size="mini" 
                    @click="viewUserProfile(scope.row.registrationId)">
                    查看用户
                  </el-button>
                </template>
              </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              @current-change="handlePageChange"
              :current-page="currentPage"
              :page-size="pageSize"
              layout="total, prev, pager, next"
              :total="totalRegistrations"
            />
          </div>
        </div>
      </div>
      
      <!-- 右侧内容区 -->
      <div class="right-content">
        <!-- 数据统计卡片 -->
        <div class="stats-card">
          <h2 class="info-title">
            <i class="el-icon-data-line"></i> 报名数据统计
          </h2>
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-value">{{ stats.todayAmount || 0 }}</div>
              <div class="stat-label">今日成交额</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.monthAmount || 0 }}</div>
              <div class="stat-label">本月成交额</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.totalAmount || 0 }}</div>
              <div class="stat-label">总成交额</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ totalRegistrations || 0 }}</div>
              <div class="stat-label">总报名数</div>
            </div>
          </div>
        </div>

        <!-- 趋势图 -->
        <div class="trend-card">
          <h2 class="info-title">
            <i class="el-icon-trend-charts"></i> 报名趋势
          </h2>
          <div class="trend-options">
            <el-radio-group v-model="trendDays" size="small" @change="loadTrendData">
              <el-radio-button :label="7">近7天</el-radio-button>
              <el-radio-button :label="30">近30天</el-radio-button>
              <el-radio-button :label="90">近90天</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-container">
            <!-- 这里可以放置echarts图表 -->
            <div v-if="trendData.length > 0" id="trend-chart" style="height: 250px;"></div>
            <el-empty v-else description="暂无数据" />
          </div>
        </div>
        
        <!-- 跟团游项目部分 -->
        <div class="popular-tours">
          <h2 class="info-title">
            <i class="el-icon-map-location"></i> 跟团游项目
          </h2>
            <div class="tour-list">
              <div class="tour-item" v-for="(tour, index) in groupTours" :key="index">
                <div class="tour-image"
     :style="{ backgroundImage: `url(${tour.groupTourImageLink})` }">
                </div>
                <div class="tour-info">
                  <h3>{{ tour.groupTourName }}</h3>
                  <div class="tour-meta">
                    <span><i class="el-icon-time"></i> {{ calculateTourDays(tour.startDate, tour.endDate) }}天</span>
                    <span><i class="el-icon-user"></i> {{ tour.recruitmentNumber }}人团</span>
                  </div>
                  <div class="tour-price">
                    <span>¥{{ tour.groupTourPrice }}</span>起
                  </div>
                  <div class="tour-desc">{{ tour.groupTourIntroduction || '暂无简介' }}</div>
                  <el-button type="primary" size="small" round @click="viewTourDetail(tour)">查看详情</el-button>
                </div>
              </div>
            </div>
        </div>
      </div>
    </div>
    
    <!-- 底部操作按钮区 -->
    <div class="action-buttons">
      <el-button @click="goBack" icon="el-icon-arrow-left">返回</el-button>
      <el-button type="primary" @click="saveInfo" :disabled="!isEditing" icon="el-icon-check">保存</el-button>
      <el-button type="danger" @click="logout" icon="el-icon-switch-button">退出登录</el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';
    export default {
      name: 'AgencyHome',
    data() {
      return {
        uploadHeaders: {
          'Authorization': localStorage.getItem('token') || ''
        },
        isEditing: false,
        originalInfo: {},
        agencyInfo: {
          travelAgencyId: null,
          travelAgencyName: '',
          officePhone: '',
          officeEmail: '',
          officeAddress: '',
          travelAgencyIntroduction: '',
          travelAgencyAvatar: '',
          principalName: '',
          principalPhone: '',
          regionId: null,
        },
       // 省份和城市字段
      selectedProvince: '',
      selectedCity: '',
      provinceOptions: [],
      cityOptions: [],
      regionOptions: [],
      regionMap: {},
      // 跟团游报名相关数据
      groupTours: [],
      registrationList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalRegistrations: 0,
      searchKeyword: '',
      dateRange: [],
      travelAgencyId: null, // 添加旅行社ID字段
      // 统计数据
      stats: {
        todayAmount: 0,
        monthAmount: 0,
        totalAmount: 0
      },
      // 趋势数据
      trendData: [],
      trendDays: 7,
      chartInstance: null
    };
  },
    async created() {
      await this.loadRegionOptions();
      await this.loadAgencyInfo();
    },
  methods: {
    // 新增一个方法用于获取完整的图片 URL
    getFullImageUrl(relativePath) {
      if (relativePath && !relativePath.startsWith('http')) {
        const baseUrl = 'http://localhost:8080';
        // 添加时间戳作为查询参数，以防止浏览器缓存
        const timestamp = new Date().getTime();
        return `${baseUrl}${relativePath}?t=${timestamp}`;
      }
      return relativePath;
    },
    async loadRegionOptions() {
      try {
        const response = await fetch('http://localhost:8080/api/regions');
        if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);

        const result = await response.json();

        // 根据实际API响应结构调整
        const data = result.data || result;

        this.regionOptions = data;
        this.provinceOptions = [...new Set(data.map(r => r.province))];

        this.regionMap = {};
        data.forEach(r => {
          if (!this.regionMap[r.province]) this.regionMap[r.province] = [];
          this.regionMap[r.province].push(r.city);
        });

        console.debug('省市数据加载成功', {
          provinces: this.provinceOptions,
          regionMap: this.regionMap
        });

      } catch (e) {
        console.error('省市数据加载失败:', e);
        this.$message.error(`省市数据加载失败: ${e.message}`);
      }
    },
    handleProvinceChange(val) {
      // 省份变化时，更新城市选项
      if (!this.regionMap || !this.regionMap[val]) {
        this.cityOptions = [];
        this.selectedCity = '';
        return;
      }
      this.cityOptions = this.regionMap[val] || [];
      // 如果当前选中的城市不在新省份下，清空
      if (!this.cityOptions.includes(this.selectedCity)) {
        this.selectedCity = '';
      }
    },

    // 头像上传成功处理
    handleAvatarSuccess(response, file) {
        console.log('handleAvatarSuccess called!');
        if (response.code === 200) {
            this.$message.success('头像上传成功');
            // 确保使用正确的URL格式，从正确的键获取数据
            this.agencyInfo.travelAgencyAvatar = this.getFullImageUrl(response['上传成功']);
            console.log('handleAvatarSuccess: response[\'上传成功\']:', response['上传成功']);
            console.log('handleAvatarSuccess: updated agencyInfo.travelAgencyAvatar:', this.agencyInfo.travelAgencyAvatar);
        } else {
            this.$message.error(response.message || '头像上传失败');
        }
    },
    // 头像上传前校验
    beforeAvatarUpload(file) {
        console.log('beforeAvatarUpload called! File:', file.name, file.type, file.size);
        const isImage = file.type.includes('image/');
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isImage) {
          this.$message.error('只能上传图片文件!');
        }
        if (!isLt2M) {
          this.$message.error('图片大小不能超过2MB!');
        }

        return isImage && isLt2M;
      },
    // 头像上传进度处理
    handleAvatarProgress(event, file, fileList) {
      console.log('handleAvatarProgress called! Progress:', event.percent);
    },
    // 头像上传失败处理
    handleAvatarError(err, file, fileList) {
      console.error('handleAvatarError called! Error:', err, 'File:', file, 'FileList:', fileList);
      this.$message.error('头像上传失败，请稍后重试。详细信息请查看控制台。');
    },
async loadAgencyInfo() {
  try {
    const loginId = localStorage.getItem('loginId');
    if (!loginId) {
      this.$message.error('未获取到用户信息，请重新登录');
      this.$router.push('/loginpage');
      return;
    }

    const response = await fetch(`http://localhost:8080/mw/travelAgency/byLoginId/${loginId}`);
    const data = await response.json();

    if (response.ok) {
      console.log('loadAgencyInfo: original data.travelAgencyAvatar:', data.travelAgencyAvatar);
      this.agencyInfo = {
        ...this.agencyInfo,
        ...data,
      };
        // 保存原始省市
  this.selectedProvince = data.province || '';
  this.selectedCity = data.city || '';
  this.$emit('agency-status-update', data.auditStatus || '未审核');
  // 保存原始信息用于取消编辑
  this.originalInfo = JSON.parse(JSON.stringify(this.agencyInfo));
      // 在加载旅行社信息时，也使用 getFullImageUrl 来处理头像路径
      if (this.agencyInfo.travelAgencyAvatar) {
        this.agencyInfo.travelAgencyAvatar = this.getFullImageUrl(this.agencyInfo.travelAgencyAvatar);
      }
      console.log('loadAgencyInfo: updated agencyInfo.travelAgencyAvatar:', this.agencyInfo.travelAgencyAvatar);
      this.travelAgencyId = data.travelAgencyId;
      this.originalInfo = JSON.parse(JSON.stringify(this.agencyInfo));
      // 赋值省市
      this.selectedProvince = data.province || '';
      this.selectedCity = data.city || '';
      if (this.selectedProvince && this.regionMap && Object.keys(this.regionMap).length > 0) {
      this.handleProvinceChange(this.selectedProvince);
    }

      // 加载依赖旅行社ID的数据
      this.loadRegistrationData();
      this.loadStatsData();
      this.loadTrendData();
      this.loadGroupTours();
    } else {
      throw new Error(data.message || '获取旅行社信息失败');
    }
  } catch (error) {
    this.$message.error(error.message);
    console.error('加载旅行社信息失败:', error);
  }
},
    calculateTourDays(startDate, endDate) {
      if (!startDate || !endDate) return '未知';

      const start = new Date(startDate);
      const end = new Date(endDate);

      // 计算天数差异（包含起始日）
      const diffTime = Math.abs(end - start);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;

      return diffDays;
    },
    // 加载跟团游项目
      async loadGroupTours() {
        this.loading = true;
        try {
          // 获取旅行社ID
          const loginId = localStorage.getItem('loginId');
          if (!loginId) {
            this.$message.error('未获取到用户信息，请重新登录');
            this.$router.push('/loginpage');
            return;
          }

          // 获取旅行社ID
          const agencyResponse = await fetch(`http://localhost:8080/mw/travelAgency/byLoginId/${loginId}`);
          const agencyData = await agencyResponse.json();
          
          if (!agencyResponse.ok || !agencyData.travelAgencyId) {
            throw new Error('获取旅行社ID失败');
          }

          const agencyId = agencyData.travelAgencyId;

          // 获取跟团游数据 - 使用与 GroupTourSend 相同的接口
          const response = await fetch(`http://localhost:8080/mw/groupToursByAgency/${agencyId}`);
          const tours = await response.json();

          // 为每个跟团游获取图片和收藏数
          const toursWithImages = await Promise.all(tours.map(async tour => {
            try {
              // 获取图片
              const imgRes = await fetch(`http://localhost:8080/mw/travelAuditImages/${tour.groupTourId}`);
              const images = await imgRes.json();
              
              // 获取收藏数
              const favRes = await fetch(`http://localhost:8080/mw/getFavoriteCount?groupTourId=${tour.groupTourId}`);
              const favoriteCount = await favRes.json();

              return {
                ...tour,
                images: images.map(img => img.groupTourImageLink),
                favoriteCount: favoriteCount.count || 0,
                // 设置默认图片
                groupTourImageLink: images.length > 0 ? images[0].groupTourImageLink : 'https://picsum.photos/600/400?random=' + Math.random()
              };
            } catch (e) {
              console.error('获取图片或收藏数失败:', e);
              return {
                ...tour,
                images: [],
                favoriteCount: 0,
                groupTourImageLink: 'https://picsum.photos/600/400?random=' + Math.random()
              };
            }
          }));

          this.groupTours = toursWithImages.filter(tour => tour.auditStatus === '通过');
        } catch (error) {
          this.$message.error(error.message || '获取跟团游项目失败');
          console.error('加载跟团游项目失败:', error);
          this.groupTours = [];
        } finally {
          this.loading = false;
        }
      },


async saveInfo() {
  try {
    const userId = localStorage.getItem('loginId');
    if (!userId) {
      this.$message.error('未获取到用户信息，请重新登录');
      this.$router.push('/loginpage');
      return;
    }

    // 根据省市查找region_id
    const region = this.regionOptions.find(
      r => r.province === this.selectedProvince && r.city === this.selectedCity
    );
    
    if (!region) {
      this.$message.error('请选择有效的省份和城市');
      return;
    }

    // 构建保存数据 - 只提交region_id
    const dataToSave = {
      travelAgencyId: this.agencyInfo.travelAgencyId,
      travelAgencyName: this.agencyInfo.travelAgencyName,
      officePhone: this.agencyInfo.officePhone,
      officeEmail: this.agencyInfo.officeEmail,
      officeAddress: this.agencyInfo.officeAddress,
      travelAgencyIntroduction: this.agencyInfo.travelAgencyIntroduction,
      principalName: this.agencyInfo.principalName,
      principalPhone: this.agencyInfo.principalPhone,
      regionId: region.regionID, // 关键修改：使用region_id
      loginId: parseInt(userId),
      auditStatus: this.agencyInfo.auditStatus || '待审核'
    };

    const response = await fetch('http://localhost:8080/mw/travelAgency/update', {
      method: 'PUT',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(dataToSave)
    });

    if (response.ok) {
      this.$message.success('旅行社信息已更新');
      this.isEditing = false;
      // 重新加载数据以显示更新后的省市信息
      await this.loadAgencyInfo();
    } else {
      const errorData = await response.json();
      throw new Error(errorData.message || '更新失败');
    }
  } catch (error) {
    this.$message.error(error.message);
    console.error('保存失败:', error);
  }
},
async loadRegistrationData() {
  this.loading = true;
  try {
    // 确保旅行社ID存在
    if (!this.agencyInfo.travelAgencyId) {
      console.error('旅行社ID不存在');
      return;
    }

    const params = {
      pageNum: this.currentPage,
      pageSize: this.pageSize,
      agencyId: this.agencyInfo.travelAgencyId,
      keyword: this.searchKeyword,
      startDate: this.dateRange?.[0] ? this.formatDateForApi(this.dateRange[0]) : null,
      endDate: this.dateRange?.[1] ? this.formatDateForApi(this.dateRange[1]) : null
    };

    // 构建查询字符串
    const queryString = Object.entries(params)
      .filter(([_, value]) => value !== null)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');

    const response = await fetch(`http://localhost:8080/gtr/agency/page/search?${queryString}`);
    const data = await response.json();

    if (response.ok) {
      this.registrationList = data.list || [];
      this.totalRegistrations = data.total || 0;
    } else {
      throw new Error(data.message || '获取报名数据失败');
    }
  } catch (error) {
    console.error('加载报名数据失败:', error);
    this.$message.error(error.message);
  } finally {
    this.loading = false;
  }
},


    // 加载统计数据
async loadStatsData() {
  try {
    const response = await fetch(`http://localhost:8080/gtr/agency/stats?agencyId=${this.agencyInfo.travelAgencyId}`);
    const data = await response.json();

    if (response.ok) {
      this.stats = data;
    } else {
      throw new Error(data.message || '获取统计数据失败');
    }
  } catch (error) {
    this.$message.error(error.message);
    console.error('加载统计数据失败:', error);
  }
},

// 修改loadTrendData方法
async loadTrendData() {
  try {
    const response = await fetch(`http://localhost:8080/gtr/agency/trend?agencyId=${this.agencyInfo.travelAgencyId}&days=${this.trendDays}`);
    const data = await response.json();
    
    if (response.ok) {
      this.trendData = data;
      // 确保DOM更新后再渲染图表
      this.$nextTick(() => {
        this.renderChart();
      });
    } else {
      throw new Error(data.message || '获取趋势数据失败');
    }
  } catch (error) {
    
    console.error('加载趋势数据失败:', error);
  }
},
cancelEdit() {
  // 重置为原始省市选择
  this.selectedProvince = this.originalInfo.province;
  this.selectedCity = this.originalInfo.city;
  // 重新加载城市选项
  this.handleProvinceChange(this.selectedProvince);
  // 恢复其他字段
  this.agencyInfo = JSON.parse(JSON.stringify(this.originalInfo));
  this.isEditing = false;
},

    // 渲染趋势图表
    renderChart() {
      if (!this.trendData || this.trendData.length === 0) return;

      // 初始化图表
      if (!this.chartInstance) {
        this.chartInstance = echarts.init(document.getElementById('trend-chart'));
      }

      // 准备图表数据
      const dates = this.trendData.map(item => item.date);
      const amounts = this.trendData.map(item => item.amount);

      // 配置图表选项
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>成交额: {c}元'
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '成交额(元)'
        },
        series: [{
          data: amounts,
          type: 'line',
          smooth: true,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(148, 112, 219, 0.8)' },
              { offset: 1, color: 'rgba(148, 112, 219, 0.1)' }
            ])
          },
          itemStyle: {
            color: '#9470db'
          }
        }],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        }
      };

      // 设置图表选项
      this.chartInstance.setOption(option);

      // 响应窗口大小变化
      window.addEventListener('resize', this.handleResize);
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },

    // 查看报名详情
    async viewRegistrationDetail(row) {
      try {
        // 获取用户ID
        const response = await axios.get(`http://localhost:8080/gtr/getUserIdByRegistration?registrationId=${row.registrationId}`);
        const userId = response.data;
        
        if (userId) {
          // 跳转到用户个人资料页面
          this.$router.push({
            name: 'UserProfileView',
            params: { id: userId }
          });
        } else {
          this.$message.error('未找到用户信息');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.$message.error('获取用户信息失败');
      }
    },
    
    // 查看用户资料
    async viewUserProfile(registrationId) {
      try {
        // 使用后端接口获取用户ID
        const response = await axios.get(`http://localhost:8080/gtr/getUserIdByRegistration?registrationId=${registrationId}`);
        const userId = response.data;
        
        if (userId) {
          // 跳转到用户个人资料页面
        this.$router.push({ name: 'UserProfileView', params: { id: userId } });
        } else {
          this.$message.error('未找到用户信息');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.$message.error('获取用户信息失败');
      }
    },
    // 处理搜索
    handleSearch() {
      this.currentPage = 1;
      this.loadRegistrationData();
    },

    // 处理分页变化
    handlePageChange(page) {
      this.currentPage = page;
      this.loadRegistrationData();
    },

    // 格式化日期显示
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    },

    // 格式化日期为API需要的格式
    formatDateForApi(date) {
      if (!date) return '';
      const d = new Date(date);
      return d.toISOString().split('T')[0];
    },
    viewTourDetail(tour) {
      this.$router.push({
        name: 'GroupTourAudit', // 使用路由名称而不是组件名称
        params: { id: tour.groupTourId }
      });
    },
    toggleEdit() {
      if (!this.isEditing) {
        this.originalInfo = JSON.parse(JSON.stringify(this.agencyInfo));
      }
      this.isEditing = !this.isEditing;
    },
    cancelEdit() {
      this.agencyInfo = JSON.parse(JSON.stringify(this.originalInfo));
      this.isEditing = false;
    },
    goBack() {
      this.$router.go(-1);
    },
    logout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('退出登录成功');
      }).catch(() => {
        this.$message.info('已取消退出');
      });
    },
    formatBusinessHours(hours) {
      if (!hours || hours.length !== 2) return '09:00 - 18:00';
      const start = hours[0];
      const end = hours[1];
      return `${start.getHours()}:${start.getMinutes().toString().padStart(2, '0')} - ${end.getHours()}:${end.getMinutes().toString().padStart(2, '0')}`;
    },
    beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize);
    // 销毁图表实例
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  }
},

    }
</script>

<style scoped>
/* 顶部横幅样式 */
.banner {
  background: linear-gradient(135deg, #d8bfd8 0%, #e5afe5 100%);
  color: #a677c7;
  padding: 60px 20px;
  text-align: center;
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(147, 112, 219, 0.3);
}

.banner::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('https://via.placeholder.com/1920x400?text=极地登山俱乐部') center/cover;
  opacity: 0.1;
}

.banner-content {
  position: relative;
  z-index: 1;
  max-width: 1200px;
  margin: 0 auto;
}

.banner h1 {
  font-size: 36px;
  margin-bottom: 10px;
  color: #7e4fa0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.slogan {
  font-size: 18px;
  color: #6a5acd;
  margin-top: 0;
  font-weight: 500;
}

/* 主要内容区布局 */
.agency-home-container {
  background-color: #ffffff;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.main-content {
  display: flex;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  gap: 30px;
}

.left-content {
  flex: 2;
  min-width: 0;
}

.right-content {
  flex: 1;
  min-width: 0;
}

/* 卡片通用样式 */
.info-card, .registration-card, .popular-tours, .stats-card, .trend-card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 25px;
  margin-bottom: 30px;
  border: 1px solid #f0f0f0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
}

.info-title {
  color: #6a5acd;
  font-size: 22px;
  margin: 0;
  display: flex;
  align-items: center;
  font-weight: 600;
}

.info-title i {
  margin-right: 10px;
  font-size: 24px;
  color: #9370db;
}

/* 审核状态标签 */
.audit-status {
  position: absolute;
  top: 2px;
  right: 430px;
  z-index: 10;
}

.audit-status .el-tag {
  font-size: 14px;
  padding: 8px 15px;
  border-radius: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

/* ========== 强制圆形头像样式（保持比例但裁剪超出部分） ========== */
.avatar-uploader {
  display: inline-block;
  width: 100px;
  height: 100px;
  position: relative;
}

.avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  width: 100px !important;
  height: 100px !important;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #9370db;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 50%;
  object-fit: cover; /* 关键修改：保持比例同时填充整个圆形区域 */
  border: 3px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.avatar-uploader .avatar-hover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: rgba(147, 112, 219, 0.7);
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}
/* 表单样式 */
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item >>> .el-form-item__label {
  color: #897fc6;
  font-weight: 600;
  font-size: 15px;
}

.description-text {
  color: #666;
  line-height: 1.6;
  margin: 0;
  white-space: pre-line;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

/* 跟团游项目列表样式 */
.tour-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tour-item {
  display: flex;
  border: 1px solid rgba(147, 112, 219, 0.2);
  border-radius: 12px;
  overflow: hidden;
  background: #ffffff;
}

.tour-image {
  width: 150px;
  height: 150px;
  background-size: cover;
  background-position: center;
  flex-shrink: 0;
}

.tour-info {
  flex: 1;
  padding: 15px;
  display: flex;
  flex-direction: column;
}

.tour-info h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #4b0082;
}

.tour-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 8px;
  font-size: 13px;
  color: #9370db;
}

.tour-meta i {
  margin-right: 5px;
}

.tour-price {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.tour-price span {
  font-size: 20px;
  font-weight: bold;
  color: #ff6600;
}

.tour-desc {
  flex: 1;
  font-size: 13px;
  color: #666;
  margin: 8px 0 12px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 表格样式 */
.table-header {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

/* 统计卡片样式 */
.stats-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.stat-item {
  background: rgba(147, 112, 219, 0.1);
  border-radius: 12px;
  padding: 20px;
  text-align: center;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #6a5acd;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #9370db;
}

/* 趋势图卡片 */
.trend-options {
  margin: 20px 0;
  text-align: center;
}

.chart-container {
  height: 250px;
  margin-top: 15px;
}

/* 底部操作按钮 */
.action-buttons {
  text-align: center;
  padding: 25px 0;
  margin-top: 30px;
  background: #ffffff;
  border-top: 1px solid rgba(147, 112, 219, 0.2);
}

.el-button {
  transition: all 0.3s ease;
  border-radius: 20px;
  padding: 12px 25px;
  font-weight: 500;
}

.el-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.el-button + .el-button {
  margin-left: 15px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .main-content {
    flex-direction: column;
  }
  
  .left-content, .right-content {
    width: 100%;
  }
  
  .info-card, .registration-card, .stats-card, .trend-card, .popular-tours {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .banner h1 {
    font-size: 28px;
  }

  .banner {
    padding: 40px 20px;
  }

  .tour-item {
    flex-direction: column;
  }

  .tour-image {
    width: 100%;
    height: 180px;
  }
  
  .stats-content {
    grid-template-columns: 1fr;
  }

  /* 移动端头像上传调整 */
  .avatar-uploader .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
  
  .avatar-uploader-icon {
    font-size: 20px;
  }
  
  .avatar-hover i {
    font-size: 16px;
  }
}

/* 平滑过渡效果 */
* {
  transition: all 0.3s ease;
}
</style>